package com.meta.scheduledInfo;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.meta.api.mapper.UserMapper;
import com.meta.api.po.UserModel;
import com.meta.common.enums.CommonConstants;
import com.meta.common.utils.DateUtil;
import com.meta.common.utils.DoubleColorUtils;
import com.meta.common.utils.RegexUtils;
import com.meta.common.utils.SendEmail;
import com.meta.kafka.service.KafkaSender;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @author ：xzw
 * @date ：Created in 2021/11/18 22:05
 * <p>
 * 双色球定时任务
 */
@Component
@Slf4j
public class DoubleColorBall {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private KafkaSender kafkaSender;

    static final List<Integer> dayIndexList = new ArrayList();

    static {
        dayIndexList.add(2);
        dayIndexList.add(4);
        dayIndexList.add(7);
    }

    static String[] redChar = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
            "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
            "21", "22", "23", "24", "25", "26", "27", "28", "29", "30",
            "31", "32", "33"};
    static String[] blueChar = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
            "11", "12", "13", "14", "15", "16"};


    static List<String> emailList = new ArrayList();

    static {
        emailList.add("597925798@qq.com");
        emailList.add("531730746@qq.com");
    }


    /**
     * 发邮箱往期最高频率数字
     * <p>
     */
    @Scheduled(cron = "22 22 22 * * ?")
    public void setHigNumRedis() {

        if (!DateUtil.isTheDayInWeekList(dayIndexList)) {
            return;
        }

        String num = "";
        //获取所有的中奖号码
        List<String> list = DoubleColorUtils.historyList("");
        num = DoubleColorUtils.analyzeInfo(list);

        getUserInfo();
        JSONObject jsonObject = null;
        try {
            for (String email : emailList) {
                jsonObject = new JSONObject();
                jsonObject.put("title", "往期最高频率数字");
                jsonObject.put("nums", num);
                jsonObject.put("email", email);
                log.info("kafka生产者发送短信");
                kafkaSender.messageSender("sendEmail", UUID.randomUUID().toString(), jsonObject.toString());
            }
        } catch (JSONException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 往期最高频率数字存放在Redis
     * <p>
     */
    @Scheduled(cron = "12 12 12 * * ?")
    public void getHigNum() {

        if (!DateUtil.isTheDayInWeekList(dayIndexList)) {
            return;
        }

        //获取所有的中奖号码
        List<String> list = DoubleColorUtils.historyList("");
        String num = DoubleColorUtils.analyzeInfo(list);

        redisTemplate.opsForValue().set(CommonConstants.double_color_ball_history_high_num_key, num);

    }


    /**
     * 获取双色球中奖号码
     * <p>
     * 每天的九点16分获取中奖号码
     */
    @Scheduled(cron = "14 16 22 * * ?")
    public void getNum() throws JSONException {

        if (!DateUtil.isTheDayInWeekList(dayIndexList)) {
            return;
        }

        String expect = DoubleColorUtils.getExpect("");
        //fix 每天都发消息
        if (!StringUtils.isEmpty(expect)) {
            getUserInfo();

            JSONObject jsonObject = null;
            for (String email : emailList) {
                //历史最高频率数字
                String info = "最高出现次数号码为：" + "<br>" + redisTemplate.opsForValue().get(CommonConstants.double_color_ball_history_high_num_key) + "<br>" + "本次中奖号码为" + "<br>" + expect + "<br>";
                //todo  你买的号码是
                Object o = redisTemplate.opsForValue().get(email);
                info = info + "您买的号码是：" + o + "<br>";
                //todo  你是否中奖
                jsonObject = new JSONObject();
                jsonObject.put("title", "本期中奖号码");
                jsonObject.put("nums", info);
                jsonObject.put("email", email);
                kafkaSender.messageSender("sendEmail", UUID.randomUUID().toString(), jsonObject.toString());
            }
        }
    }


    /**
     * 一千万奖金
     * 每天14点14分执行
     */
    @Scheduled(cron = "14 14 14 * * ?")
    public void money() {

        if (!DateUtil.isTheDayInWeekList(dayIndexList)) {
            return;
        }
        System.out.println("xczxczxc哈哈哈" + Charset.defaultCharset());

//        getUserInfo();

        //从数据库读取接收人账号数据

        //只发10个
        int num = 0;
        for (String email : emailList) {

            if (num > 10) {
                return;
            }
            //生成彩票数字
            String colorNum = getColorNum();

//            String info = "最高出现次数号码为：" + "<br>" + redisTemplate.opsForValue().get(CommonConstants.double_color_ball_history_high_num_key) + "<br>" + "您的幸运号码为" + "<br>" + colorNum;
            String info = "最高出现次数号码为：" + "<br>" + null + "<br>" + "您的幸运号码为" + "<br>" + colorNum;

            //发送邮件  todo
            SendEmail.sendQQEmail(info, email, "您的双色球一千万大奖号码");

            //将生成中奖号码存入redis，key是邮箱
//            redisTemplate.opsForValue().set(email, colorNum);
            num++;
        }


        System.out.println("结束！");

    }

    private void getUserInfo() {

        //查询用户邮箱数据
        List<UserModel> userModels = userMapper.selectAll();
        if (CollectionUtils.isNotEmpty(userModels)) {
            for (UserModel userModel : userModels) {
                String email = userModel.getEmail();
                if (!StringUtils.isEmpty(email) && RegexUtils.checkEmail(email)) {
                    log.error("request email : {}", userModel.getEmail());
                    if (!emailList.contains(email)) {
                        emailList.add(userModel.getEmail());
                    }
                }
            }
        }
    }

    /**
     * 生成彩票数字
     */
    public static String getColorNum() {

        List<String> redList = new ArrayList<>();
        List<String> blueList = new ArrayList<>();
        for (String c : redChar) {
            redList.add(c);
        }
        for (String c : blueChar) {
            blueList.add(c);
        }

        String TenMillionBonusNum = "";
        List<Integer> nums = new ArrayList<>();
        Random r = new Random();

        for (int i = 32; i > 26; i--) {
            System.out.print("现在抽取您的第" + (33 - i) + "个吉祥数字     ");
            int index = r.nextInt(i);
            String num = redList.get(index);
            System.out.println("第" + (33 - i) + "个吉祥数字: " + num);
            redList.remove(index);
            nums.add(Integer.valueOf(num));
        }

        Object[] a = nums.toArray();
        Arrays.sort(a);
        System.out.println("nums = " + nums);
        String numStr = "";
        for (int i = 0; i < a.length; i++) {
            Integer num = (Integer) a[i];
            if (num < 10) {
                numStr = "0" + num;
            } else {
                numStr = num + "";
            }
            if (i == 0) {
                TenMillionBonusNum = numStr + "  ";
            } else {
                TenMillionBonusNum = TenMillionBonusNum + numStr + "  ";
            }
        }
        System.out.print("现在抽取您的第" + 7 + "个吉祥数字     ");
        int index = r.nextInt(16);
        String num = blueList.get(index);
        System.out.println("第" + 7 + "个吉祥数字: " + num);
        nums.add(Integer.valueOf(num));
        TenMillionBonusNum = TenMillionBonusNum + num + "  ";
        System.out.println("恭喜主人喜中1000万RMB，您的兑奖号码为：" + TenMillionBonusNum);
        return TenMillionBonusNum;
    }
}
